package interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import pojo.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author jesse
 * @Date 2019/5/28 11:08
 * @Version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //获取请求的RUi:去除http:localhost:8080这部分剩下的
        logger.info("拦截器生效");
        logger.info("请求路径"+request.getRequestURI());
        String uri = request.getRequestURI();
        //UTL:除了signin和valid是可以公开访问的，其他的URL都进行拦截控制
        if (uri.contains("/signin") || uri.contains("/valid")) {
            logger.info("公开访问");
            request.setAttribute("msg","成功");
            return true;
        }
        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        logger.info("user="+user);
        //判断session中是否有用户数据，如果有，则返回true，继续向下执行
        if (user != null) {
            logger.info("已登录,user="+user);
//            System.out.println("user");
            request.setAttribute("msg","成功");
            return true;
        }else {
            //不符合条件的给出提示信息，并转发到登录页面
            logger.warn("还没有登录,即将返回登录页面");
            request.setAttribute("msg", "您还没有登录，请先登录！");
            request.getRequestDispatcher("/WEB-INF/view/signin/signin.html").forward(request, response);
//            response.sendRedirect("/SysM/signin");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
